<template>
  <div class="app-container">

    <div class="filter-container">
      <el-row>

        <el-input
          v-model="listQuery.key_word"
          placeholder="关键字"
          style="width: 200px;"
          class="filter-item"
        />
        <el-button

          class="filter-item"
          type="info"
          size="mini"
          style="width: 60px;"
          @click="getRolesList"
        >搜索
        </el-button>
        <el-button
          class="filter-item"
          type="primary"
          size="mini"
          icon="el-icon-plus"
          style="float: right"
          @click="handleAddRole"
        >新建角色
        </el-button>
      </el-row>
    </div>

    <el-table v-loading="loading" :data="rolesList" style="width: 100%;margin-top:30px;" :size="table_size">
      <el-table-column v-for="(ctl,index) in table_ctl" :sortable="ctl.sortable" :key="index" :label="ctl.label" :prop="ctl.prop" v-if="ctl.visiable" :width="ctl.prop=='description'?'':'220'"
                       :align="ctl.prop=='description'?'center':'center'"></el-table-column>
      <el-table-column label="操作" width="200" align="center" class-name="small-padding fixed-width">
        <template slot="header" slot-scope="scope">
          <span style="margin-right: 15px">操作</span>
          <el-tooltip class="item" effect="dark" :hide-after="500" content="设置列" placement="top">
            <el-popover
              placement="left"
              title="设置列"
              width="200"
              trigger="click"
              content="设置列">
              <div v-for="(ctl,index) in table_ctl" :key="index" class="margin-top-xs">
                <el-switch v-model="ctl.visiable" active-text="" inactive-text="" active-color="#13ce66" inactive-color="#666666"></el-switch>
                <span>{{ctl.label}}</span>
              </div>
              <el-button slot="reference" icon="el-icon-setting" circle type="text"></el-button>
            </el-popover>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" :hide-after="500" content="行间距" placement="top">
            <el-popover
              placement="left"
              title="行间距"
              trigger="click"
              content="选择间距">
              <el-radio-group v-model="table_size" size="mini">
                <el-radio-button label="medium">大</el-radio-button>
                <el-radio-button label="small">中</el-radio-button>
                <el-radio-button label="mini">小</el-radio-button>
              </el-radio-group>
              <el-button slot="reference" icon="el-icon-crop" circle type="text"></el-button>
            </el-popover>
          </el-tooltip>
        </template>
        <template slot-scope="scope">
          <el-button circle type="text" size="mini" @click="getRolesDetail(scope.row.id)">编辑</el-button>
          <el-button circle type="text" size="mini" @click="handleDelete(scope)">删除</el-button>
<!--          <div>-->
<!--            <el-tooltip class="item" effect="dark" :hide-after="500" content="编辑" placement="top">-->
<!--              <el-button circle icon="el-icon-edit" class="my-blue" @click="getRolesDetail(scope.row.id)"></el-button>-->
<!--            </el-tooltip>-->
<!--            <el-tooltip class="item" effect="dark" :hide-after="500" content="删除" placement="top">-->
<!--              <el-button class="my-red" circle icon="el-icon-delete" @click="handleDelete(scope)"></el-button>-->
<!--            </el-tooltip>-->
<!--          </div>-->
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'角色编辑':'新建角色'">
      <el-form :model="role" label-width="120px" label-position="left">
        <el-form-item label="角色名：">
          <el-input v-model="role.name" placeholder="角色名"/>
        </el-form-item>
        <el-form-item label="描述：">
          <el-input
            v-model="role.description"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="角色描述"
          />
        </el-form-item>

        <el-form-item label="菜单">
          <el-row v-for="(item,key) in routes" :key="key" :name="key">
            <el-row style="border-bottom:1px solid lightgrey;margin-top:15px;">
              <el-col :span="12">
                <!--
                  <el-checkbox
                    v-model="_item.checked"
                    @change="routeSelectChange(_item,$event)"
                  >{{ _item.title }}</el-checkbox>
                -->
                <label>{{ item.title }}</label>
              </el-col>
            </el-row>

            <el-row v-for="(_item,_key) in item.children" :key="_key" style="margin-left:12px;">
              <el-col :span="12">
                <!--
                  <el-checkbox
                    v-model="_item.checked"
                    @change="routeSelectChange(_item,$event)"
                  >{{ _item.title }}</el-checkbox>
                -->
                <input
                  v-model="_item.checked"
                  type="checkbox"
                  @change="routeSelectChange(_item,item,key)"
                />
                <label>{{ _item.title }}</label>
              </el-col>
              <el-col :span="12">
                <el-col :span="6">
                  <input v-model="_item.add" type="checkbox"/>
                  <label>添加</label>
                </el-col>
                <el-col :span="6">
                  <input v-model="_item.del" type="checkbox"/>
                  <label>删除</label>
                </el-col>
                <el-col :span="6">
                  <input v-model="_item.edit" type="checkbox"/>
                  <label>编辑</label>
                </el-col>
                <el-col :span="6">
                  <input v-model="_item.query" type="checkbox"/>
                  <label>查询</label>
                </el-col>
              </el-col>
            </el-row>
          </el-row>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" :loading="updating" @click="submit">确认</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="表格列编辑"
      :visible.sync="table_dialog_form_visiable"
      style="width: 100%;"
      custom-class="dialogwidth">
      <el-form
        ref="dataForm"
        label-position="left"
        label-width="200px">
        <div class="lb">
          <el-form-item :label="ctl.label + '：'" v-for="(ctl,index) in table_ctl" :key="index">
            <el-switch v-model="ctl.visiable" active-text="可见" inactive-text="不可见" active-color="#13ce66" inactive-color="#666666"></el-switch>
          </el-form-item>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="table_dialog_form_visiable = false" type='primary'>确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { getRole, addRole, removeRole, editRole, getRoleDetail } from '@/api/system'
  import { getMenuList } from '@/api/route'

  const defaultRole = {
    key: '',
    name: '',
    description: '',
    routes: []
  }

  export default {
    data() {
      return {
        activeNames: [0, 1, 2, 3, 4],
        updating: false,
        role: Object.assign({}, defaultRole),
        routes: [],
        loading: false,
        rolesList: [],
        table_dialog_form_visiable: false,
        table_size:'mini',
        table_ctl: [
          {
            label: 'ID',
            prop: 'id',
            sortable: false,
            visiable: true,
            formatter: null
          },
          {
            label: '角色名',
            prop: 'name',
            sortable: false,
            visiable: true,
            formatter: null
          },
          {
            label: '描述',
            prop: 'description',
            sortable: false,
            visiable: true,
            formatter: null
          }
          // {
          //   label:'更新时间',
          //   prop:'updateTime',
          //   sortable: false,
          //   visiable:true,
          //   formatter:null,
          // },
          // {
          //   label:'创建时间',
          //   prop:'createTime',
          //   sortable: false,
          //   visiable:true,
          //   formatter:null,
          // },
        ],
        dialogVisible: false,
        dialogType: 'new',
        checkStrictly: false,
        selectRoutes: [],
        listQuery: {}
      }
    },
    computed: {
      routesData() {
        return this.routes
      }
    },
    created() {
      // Mock: get all routes and roles list from server
      this.getRolesList()
      this.getRoutes()
      // console.log("store:"+JSON.stringify(this.$store.getters.routes));
    },
    methods: {
      // 二级菜单选中事件
      routeSelectChange(row, item, index) {
        // 如果是选中 , 判断已选中的列表有没有改路由, 没有则加入
        // 如果是取消选中 , 判断列表有没有该路由, 有则删除

        // 如果取消,则增删改查也设置为取消
        if (!row.checked) {
          row.add = false
          row.edit = false
          row.query = false
          row.del = false
        }
        // 如果选中, 则增删改查也设置选中
        else {
          row.add = true
          row.edit = true
          row.query = true
          row.del = true
        }
        this.$set(this.routes, index, item)
      },
      //修改添加角色
      submit() {
        this.updating = true
        var _this = this
        _this.selectRoutes.length = 0
        _this.routes.forEach((route) => {
          var add = false
          if (route.children) {
            route.children.forEach((chi) => {
              if (chi.checked) {
                add = true
                _this.selectRoutes.push(chi)
              }
            })
          }
          if (add) {
            var temp = Object.assign({}, route)
            _this.selectRoutes.push(temp)
          }
        })

        var para = {
          id: this.role.id,
          description: this.role.description,
          name: this.role.name,
          routes: {}
        }

        this.selectRoutes.forEach((element) => {
          para.routes[element.id] = [
            element.add,
            element.del,
            element.edit,
            element.query
          ]
        })
        if (this.dialogType === 'edit') {
          editRole(para).then((res) => {
            this.$message({
              type: 'success',
              message: '修改成功'
            })
            _this.updating = false
            _this.dialogVisible = false
            _this.getRolesList()
          })
        } else {
          addRole(para).then((res) => {
            this.$message({
              type: 'success',
              message: 'add success!'
            })
            _this.updating = false
            _this.dialogVisible = false
            _this.getRolesList()
          })
        }
      },
      //获取路由数据
      getRoutes() {
        var _this = this
        getMenuList().then((res) => {
          _this.routes = res.items
        })
      },
      //获取角色数据
      getRolesList() {
        var _this = this
        _this.loading = true
        getRole().then((res) => {
          _this.rolesList = res.items
          _this.loading = false
        })
      },
      //获取角色详细信息
      getRolesDetail(ID) {
        var _this = this
        getRoleDetail(ID).then((res) => {
          _this.handleEdit(res.items)
        })
      },
      // 显示添加角色dialogue
      handleAddRole() {
        this.role = Object.assign({}, defaultRole)
        // 新建的角色 , 清除所有选中权限
        this.routes.forEach((element) => {
          if (element.children) {
            element.children.forEach((chi) => {
              chi.checked = false
              chi.add = false
              chi.del = false
              chi.edit = false
              chi.query = false
            })
          }
        })

        this.dialogType = 'new'
        this.dialogVisible = true
      },
      // 显示修改角色dialogue
      handleEdit(row) {
        let _this = this
        _this.role = Object.assign({}, row)
        _this.routes.forEach((route) => {
          if (route.children) {
            route.children.forEach((chi) => {
              chi.checked = false
              chi.add = false
              chi.del = false
              chi.edit = false
              chi.query = false
            })
          }
        })

        _this.routes.forEach((route) => {
          if (route.children) {
            route.children.forEach((chi) => {
              if (_this.role.routes) {
                _this.role.routes.forEach((_route) => {
                  if (_route.route_id === chi.id) {
                    chi.checked = true
                    chi.add = _route.permission[0]
                    chi.del = _route.permission[1]
                    chi.edit = _route.permission[2]
                    chi.query = _route.permission[3]
                  }
                })
              }
            })
          }
        })

        this.dialogType = 'edit'
        this.dialogVisible = true
        this.checkStrictly = true
      },
      //删除角色
      handleDelete({ $index, row }) {
        this.$confirm('确定要删除' + row.name + '该角色吗?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async() => {
            removeRole(row.id).then((res) => {
              if (res.code === 20000) {
                this.rolesList.splice($index, 1)
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
              }
            })
          })
          .catch((err) => {
            console.error(err)
          })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .app-container {
    .roles-table {
      margin-top: 30px;
    }

    .permission-tree {
      margin-bottom: 30px;
    }
  }

  .permission_bar {
    div {
      float: left;
      margin-right: 12px;
    }
  }



  input[type="checkbox"] {
    width: 15px;
    height: 15px;
  }
</style>
